
// 作者：曾浩南
// 登录的接口
const express = require("express");//得到一个express对象
const router = express.Router();
const db = require("../model/db");

const crypto = require("crypto");//引用加密模块

//添加用户
router.post("/", async (req, res) => {
    const md5 = crypto.createHash("md5");//使用MD5算法创建hash加密对象
    const data = await db.User.create({
        mobile: req.body.mobile,
        pwd: md5.update(req.body.pwd).digest("hex"),
        isAdmin: req.body.isAdmin
    });
    res.send({
        code: 0,
        message: "",
        data
    });
})

//删除用户
router.delete("/:id", async (req, res) => {

    await db.User.deleteOne({//条件对象
        _id: db.ObjectId(req.params.id),//类型转换
    })
    res.send({
        code: 0,
        message: "",
        count,
        data
    });
})


//修改用户
router.put("/:id", async (req, res) => {
    await db.User.updateOne({//条件对象
        _id: req.params.id
    }, req.body)
    res.send({
        code: 0,
        message: "",
        data
    });
})


// 查询所有用户
router.get("/", async (req, res) => {
    if (!req.query.field) {//默认按照id排序
        req.query.field = "_id";

    }
    if (!req.query.sort) {//默认按照升序排序
        req.query.sort = "asc";
    }
    //拼接排序字符串
    let s = req.query.field;
    if (req.query.sort === "desc") {
        s = "-" + s;
    }

    //处理分页
    if (!req.query.page) {
        req.query.page == 1;//页索引默认为1
    }
    if (!req.query.limit) {
        req.query.limit == 10;//页容量 默认为10
    }
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);

    let condition = {};
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i") //不区分大小写
        condition = {
            $or: [{
                mobile: {
                    $regex: exp
                }
            },]
        };
    }
    const data = await db.User.find(condition).sort(s).skip((page - 1) * limit).limit(limit);//升序降序 
    const count = await db.User.count(condition);
    res.send({
        code: 0,
        message: "",
        count,
        data
    });
})


//验证
router.post("/login", async (req, res) => {

    const md5 = crypto.createHash("md5");//使用MD5算法创建hash加密对象

    // 根据传递的账号密码，从数据库中匹配用户，如果找到用户，将用户对象响应，如果没有找到，响应false
    const data = await db.User.findOne({ mobile: req.body.mobile, pwd: md5.update(`${req.body.pwd}`).digest("hex"), });

    // console.log("router:", data);
    if (data != null && data.isAdmin) {
        //响应的结果中包含cookie
        res.cookie("userId", "iouoiauwor19234", {
            maxAge: 7 * 24 * 60 * 60 * 1000,//有效期
            // signed: true
        })
        res.send(true);
        return;
    }
    res.send(false);

})

//得到单个用户
router.get("/:id", async (req, res) => {
    const data = await db.User.findById(req.params.id)
    res.send(data);
})

router.post("/isAdmin/:id", async (req, res) => {
    const data = await db.User.findById(req.params.id);
    if (data.isAdmin == true) {
        data.isAdmin = false;
    } else {
        data.isAdmin = false;
    }
    await db.User.updateOne({ _id: db.ObjectId(req.params.id) }, data);
    res.send(true);
})

module.exports = router;
